//
//  QSRefreshControl.swift
//  QSActivityIndicatorView
//
//  Created by 火星人 on 2017/11/7.
//  Copyright © 2017年 火星人. All rights reserved.
//

import UIKit


public enum QSRefreshPosition {
    case top
    case left
    case bottom
    case right
}

var windowTouchesEnd = false

public class QSRefreshControl: NSObject {
    
    var scrollView: UIScrollView?
    lazy var position = QSRefreshPosition.top
    var activityIndicator: QSActivityIndicatorView?
    var refreshHandle: ((UIScrollView, QSActivityIndicatorView) -> ())?
    lazy var spinning = false
    
    public func bindTo(_ scrollView: UIScrollView, refreshHandle: @escaping ((UIScrollView, QSActivityIndicatorView) -> ())) {
        
        if self.scrollView != scrollView {
            unbind()
            self.scrollView = scrollView
            self.activityIndicator = QSActivityIndicatorView()
            self.activityIndicator?.frame = CGRect(x: -200, y: -200, width: 100, height: 100)
            activityIndicator?.blockHeight = 3
            activityIndicator?.hollowR = 7
            activityIndicator?.progressTintColor = UIColor(red: 103 / 255.0, green: 112 / 255.0, blue: 127 / 255.0, alpha: 1)
            activityIndicator?.resetUI()
            scrollView.superview?.addSubview(activityIndicator!)
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
            
            self.refreshHandle = refreshHandle
        }
    }
    
    @objc private func sss(){
        print(#function)
    }
    
    public func unbind(){
        
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
        activityIndicator?.removeFromSuperview()
        scrollView = nil
        activityIndicator = nil
    }
    
    public func start(){
        
    }
    
    public func stop(){
        activityIndicator?.finish()
        perform(#selector(sstop), with: nil, afterDelay: 0.5)
    }
    
    @objc private func sstop(){
        spinning = false
    }
    
    public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let point = change?[NSKeyValueChangeKey.newKey] as? CGPoint
        if let point = point {
            observe(point)
        }
    }

    @objc private func observe(_ point: CGPoint){
        
        if let scrollView = scrollView, let activityIndicator = activityIndicator {
            switch position {
            case .top:
                
                activityIndicator.startPosition = .top
                if !spinning {
                    
                    activityIndicator.center = CGPoint(x: scrollView.superview!.frame.width * 0.5, y: activityIndicator.frame.size.height * 0.5 + scrollView.contentInset.top + 10)
                    
                    let p = (point.y + scrollView.contentInset.top) / -80
                    setP(p, scrollView: scrollView, activityIndicator: activityIndicator)
                    print(p)
                }
                break
                
            case .bottom:
                
                activityIndicator.startPosition = .top
                if !spinning {
                    
                    activityIndicator.center = CGPoint(x: scrollView.superview!.frame.width * 0.5, y: scrollView.frame.size.height - activityIndicator.frame.size.height * 0.5 + scrollView.contentInset.bottom - 10)
                    
                    var d = point.y - scrollView.contentInset.bottom + scrollView.contentInset.top
                    if scrollView.contentSize.height > scrollView.frame.size.height {
                        d = point.y - scrollView.contentInset.bottom - (scrollView.contentSize.height - scrollView.frame.size.height) + scrollView.contentInset.top
                    }
                    let p = d / 80
                    setP(p, scrollView: scrollView, activityIndicator: activityIndicator)
                }
                break
                
            case .left:
                
                activityIndicator.startPosition = .left
                if !spinning && point.x < 0 {
                    
                    activityIndicator.center = CGPoint(x: 10 + activityIndicator.frame.size.width * 0.5, y: scrollView.frame.size.height * 0.5)
                    
                    let d = -point.x
                    setP(d / 80, scrollView: scrollView, activityIndicator: activityIndicator)
                }
                break
                
            case .right:
                
                activityIndicator.startPosition = .right
                if !spinning && point.x > 0 {
                    
                    activityIndicator.center = CGPoint(x: scrollView.frame.size.width - activityIndicator.frame.size.width * 0.5 - 10, y: scrollView.frame.size.height * 0.5)
                    
                    let d = point.x
                    setP(d / 80, scrollView: scrollView, activityIndicator: activityIndicator)
                }
                break
            }
        }
    }
    
    fileprivate func setP(_ p: CGFloat, scrollView: UIScrollView, activityIndicator: QSActivityIndicatorView){
        
        activityIndicator.progress = p
        if activityIndicator.progress == 0 {
            activityIndicator.isHidden = true
        }
        else {
            activityIndicator.isHidden = false
            if activityIndicator.progress == 1 {
                activityIndicator.spin()
                spinning = true
                refreshHandle?(scrollView, activityIndicator)
            }
        }
    }
    
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
        activityIndicator?.removeFromSuperview()
    }
}
